package guiservice.client;

import guiservice.common.controls.Control;
import guiservice.common.controls.handlers.KeyEventArgs;
import guiservice.common.controls.handlers.MouseEventArgs;

import java.util.concurrent.ConcurrentHashMap;

public class EventHandler {

    private static EventHandler instance;

    public static EventHandler getInstance() {
        if (instance == null) {
            instance = new EventHandler();
        }
        return instance;
    }

    private final ConcurrentHashMap<Long, MouseEventHandler> mapIdToMouseEventHandler = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<Long, KeyEventHandler> mapIdToKeyEventHandler = new ConcurrentHashMap<>();

    public <T extends Control> void addMouseEventListener(T control, MouseEventHandler<T> handler) {
        mapIdToMouseEventHandler.put(control.getId(), handler);
    }

    public <T extends Control> void addKeyEventListener(T control, KeyEventHandler<T> handler) {
        mapIdToKeyEventHandler.put(control.getId(), handler);
    }

    public <T extends Control> void handleEvent(T control, MouseEventArgs args) {
        MouseEventHandler mouseEventHandler = mapIdToMouseEventHandler.get(control.getId());
        if (mouseEventHandler != null) {
            mouseEventHandler.handler(control, args);
        }
    }

    public <T extends Control> void handleEvent(T control, KeyEventArgs args) {
        KeyEventHandler keyEventHandler = mapIdToKeyEventHandler.get(control.getId());
        if (keyEventHandler != null) {
            keyEventHandler.handler(control, args);
        }
    }

}
